<template>
  <div class="voice">
    <!--弹框-->
    <el-dialog
      width="40%"
      top="200px"
      modal-class="voice_item"
      v-model="visible"
      :close-on-click-modal="false"
    >
      <div class="voice_body">
        <div class="process">
          <el-progress :percentage="second">{{ formatTime(second) }}</el-progress>
        </div>
        <div class="action">
          <el-button size="small" @click="sendVoice">发送</el-button>
          <el-button size="small" @click="cancel">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <!--图标-->
    <i title="语音" class="iconfont icon-yuyin" @click="getVoice" />
  </div>
</template>

<script setup>
import { getCurrentInstance, ref } from "vue";
import { useUserInfoStore } from "@/stores/UserInfoStore";

const { proxy } = getCurrentInstance();
const userInfoStore = useUserInfoStore();

const props = defineProps({
  contactId: {
    type: String,
  },
});

const mediaRecorder = ref();
const visible = ref(false);
const second = ref(0);
const name = ref("");
const timer = ref(0);
const isCancel = ref(false);
const getVoice = () => {
  navigator.mediaDevices
    .getUserMedia({ audio: true })
    .then(function (stream) {
      mediaRecorder.value = new MediaRecorder(stream);
      mediaRecorder.value.start();
      visible.value = true;
      timer.value = setInterval(() => second.value++, 1000);
      mediaRecorder.value.addEventListener("dataavailable", async function (event) {
        clearInterval(timer.value);
        if (isCancel.value) {
          proxy.$message.info("取消录音");
          return;
        }
        const audioFile = new Blob([event.data], { type: "audio/wav" });
        const fileOfBlob = new File([audioFile], new Date().getTime() + ".wav");
        const formData = new FormData();
        formData.append("file", fileOfBlob);
        name.value = fileOfBlob.name;
        const res = await proxy.Api.minioUpload(formData);
        if (res.code !== 200) {
          proxy.$message.error(res.message);
          return;
        }
        send(res.data);
      });
    })
    .catch(function (error) {
      proxy.$message.error("用户取消录音");
      console.error(error);
    });
};

const send = async (url) => {
  const prefix = props.contactId.substring(0, 1);
  if (prefix === "U") {
    const res = await proxy.Api.sendPrivateMessage({
      deduplicationId: proxy.UniqueId.generateUniqueUserId(),
      sendUserId: userInfoStore.getInfo().userId,
      contactId: props.contactId,
      messageType: "voice",
      messageContent: url,
      fileSize: second.value,
      fileName: name.value,
    });
    if (res.code == 114) {
      proxy.Confirm({
        message: res.message,
        okfun: () => {
          addContact(props.currentChatUser.contactId, res.code);
        },
        okText: "重新申请",
      });
    } else if (res.code == 200) {
      proxy.$message.success("语音已发送");
    }
    return;
  } else if (prefix === "G") {
    const res = await proxy.Api.sendClusterMessage({
      deduplicationId: proxy.UniqueId.generateUniqueClusterId(),
      sendUserId: userInfoStore.getInfo().userId,
      contactId: props.contactId,
      messageType: "voice",
      messageContent: url,
      fileSize: second.value,
      fileName: name.value,
    });
    if (res.code === 119) {
      proxy.Confirm({
        message: res.message,
        okfun: () => {
          addContact(props.currentChatUser.contactId, res.code);
        },
        okText: "重新申请",
      });
    } else if (res.code === 200) {
      proxy.$message.success("语音已发送");
    }
  }
  cancel();
  return;
};

const sendVoice = () => {
  mediaRecorder.value.stop();
  visible.value = false;
  isCancel.value = false;
};

const cancel = () => {
  second.value = 0;
  isCancel.value = true;
  mediaRecorder.value.stop();
  visible.value = false;
};

function formatTime(seconds) {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const remainingSeconds = seconds % 60;
  const formattedHours = hours < 10 ? "0" + hours : hours;
  const formattedMinutes = minutes < 10 ? "0" + minutes : minutes;
  const formattedSeconds =
    remainingSeconds < 10 ? "0" + remainingSeconds : remainingSeconds;
  return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`;
}
</script>

<style lang="scss" scoped>
.voice {
  .iconfont {
    margin-left: 10px;
    cursor: pointer;
  }
}
.voice_item {
  .el-dialog__header {
    // 隐藏x
    display: none;
  }

  .voice_body {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 15px;

    .process {
      width: 60%;
    }
  }
}
</style>
